package com.demo.media3demo

import android.net.Uri
import android.os.Bundle
import android.os.Environment
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import timber.log.Timber
import timber.log.Timber.DebugTree
import java.io.File

class MainActivity : AppCompatActivity() {
    private val MP4 = ".mp4"
    private val MKV = ".mkv"
    private val AVI = ".avi"
    private val RMVB = ".rmvb"
    private val playerView: PlayerView by lazy { findViewById(R.id.player_view) }
    private var mPlayer: ExoPlayer? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Timber.plant(DebugTree())
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }

        initPlayer()
    }

    private fun initPlayer() {
        val playlist: MutableList<MediaItem> = mutableListOf()
        val screenProtectFolder =
            File(Environment.getExternalStorageDirectory(), "Jetinno/ScreenProtect")
        if (screenProtectFolder.exists()) {
            for (childFile in screenProtectFolder.listFiles()) {
                if (childFile.isFile) {
                    val childFileName = childFile.name
                    if (childFileName.startsWith(".")) { //防止缓存文件
                        continue
                    }
                    if (childFileName.endsWith(MP4) ||
                        childFileName.endsWith(MKV) ||
                        childFileName.endsWith(AVI) ||
                        childFileName.endsWith(RMVB)
                    ) {
                        val mediaItem = MediaItem.fromUri(Uri.fromFile(childFile))
                        playlist.add(mediaItem)
                    }
                }
            }
        }
        if (playlist.isNotEmpty()) {
            if (mPlayer == null) {
                // 创建播放器
                val player = ExoPlayer.Builder(this)
                    .build()
                mPlayer = player
                playerView.player = player
                // 准备媒体源
                player.repeatMode = Player.REPEAT_MODE_ALL //全集循环播放
                player.setMediaItems(playlist)
                player.prepare()
                player.playWhenReady

                player.addListener(object : Player.Listener {
                    override fun onPlaybackStateChanged(playbackState: Int) {
                        when (playbackState) {
                            Player.STATE_IDLE -> {
                                Timber.d("播放器空闲，未准备任何媒体")
                            }
                            Player.STATE_BUFFERING -> {
                                Timber.d("正在缓冲数据")
                            }
                            Player.STATE_READY -> {
                                Timber.d("已准备好播放")
                            }
                            Player.STATE_ENDED -> {
                                Timber.d("播放结束")
                            }
                        }
                    }

                    override fun onIsPlayingChanged(isPlaying: Boolean) {
                        super.onIsPlayingChanged(isPlaying)
                        Timber.d("播放状态改变：$isPlaying")
                    }

                    override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
                        super.onMediaItemTransition(mediaItem, reason)
                        Timber.d("媒体项切换：$mediaItem")
                        when(reason){
                            Player.MEDIA_ITEM_TRANSITION_REASON_AUTO->{
                                Timber.d("自动切换媒体项")
                            }
                            Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT->{
                                Timber.d("媒体项重复播放")
                            }
                            Player.MEDIA_ITEM_TRANSITION_REASON_SEEK->{
                                Timber.d("媒体项跳转")
                            }
                        }
                    }

                })
            }
            mPlayer?.let {
                it.play()
            }
        }

    }

    override fun onDestroy() {
        mPlayer?.release()
        mPlayer = null
        super.onDestroy()
    }
}